package com.huatai.paas.utils;

import okhttp3.*;
import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

public class HttpsUtil {

	public static OkHttpClient getUnsafeOkHttpClient() {
		try {
			// 创建信任所有证书的TrustManager
			final TrustManager[] trustAllCerts = new TrustManager[]{
				new X509TrustManager() {
					@Override
					public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
					}

					@Override
					public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
					}

					@Override
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {
						return new java.security.cert.X509Certificate[]{};
					}
				}
			};

			// 安装信任管理器
			final SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

			// 创建TrustAllHostnameVerifier
			final HostnameVerifier trustAllHostnames = new HostnameVerifier() {
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			};

			// 创建OkHttpClient并配置
			return new OkHttpClient.Builder()
				.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
				.hostnameVerifier(trustAllHostnames)
				.connectTimeout(30, TimeUnit.SECONDS)
				.readTimeout(30, TimeUnit.SECONDS)
				.writeTimeout(30, TimeUnit.SECONDS)
				.build();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
